package com.mysecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysecurity.pojo.Permission;
import com.mysecurity.pojo.Role;
import com.mysecurity.pojo.SecurityUser;
import com.mysecurity.pojo.User;
import com.mysecurity.service.PermissionService;
import com.mysecurity.service.RoleService;
import com.mysecurity.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jane
 * @date 2024-06-28 16:25
 */
@Component
public class DBUserDetailsService  implements UserDetailsService {
    @Resource
    UserService userService;

    @Resource
    RoleService roleService;


    @Resource
    PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //认证  && 授权
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);

        User user = userService.getOne(queryWrapper);

        if (null== user){
            throw  new UsernameNotFoundException("用户名不存在");
        }

        Role role =roleService.getRoleListByUserId(user.getId()).get(0);
        List<Permission> permissions=new ArrayList<>();
        if (null!=role){
            //根据角色id查找相应的系统权限
            permissions=permissionService.getPermissionByRoleId(role.getId()); //角色id
        }

        List<String> stringList = permissions.stream().map(Permission::getCode).collect(Collectors.toList());

        return new SecurityUser(user,stringList);
    }
}
